﻿var DetailArray = new Array();  
var orderTemplate = {};


$(function () {

    $('#divHelp').dialog({
        width: 600,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $("#btnHelp").click(function () {
        $('#divHelp').dialog('open');
    });

    $.ajax({
        url: "/System/GetOriginalTemplate",
        type: 'GET',
        cache: false,
        async: true,
        data: {},
        success: function (result) {

            if (result.code == 0) {
                DetailArray = result.data;
                GenerateTemplate();
            }
            else {
                alert("获取模板信息失败");
            }
        },
        error: function (e) {
            alert("获取模板信息失败");
        }
    });


    $('#btnAddCategory').click(function () {
        var divContainer = $("#divCategories");
        var table = CreateNewCategory();
        $($("table").get(0)).before(table);
    });

    $('#btnSave,#btnSave1').click(function () {
        if (CheckInput()) {
            GetTemplateObject();
            if (DetailArray == null || DetailArray.length == 0) {
                $(".errorSpan").text('至少应该包含一个分类信息');
                return;
            }

            if (confirm("确定保存模板吗？")) {

                $.ajax({
                    url: "/System/UpdateOrderTemplate",
                    type: 'POST',
                    cache: false,
                    dataType: 'json',
                    data: { data: JSON.stringify(DetailArray) },
                    success: function (result) {
                        if (result.code == 0) {
                            alert("保存成功");
                            location.href = "/System/OrderTemplate";
                        }
                        else {
                            $(".errorSpan").text(result.message);
                        }
                    },
                    error: function (e) {
                        $(".errorSpan").text("保存失败");
                    }
                });
            }
        }
    });
});

var comapre = function (x, y) {
    return x.id.localeCompare(y.id); 
}

function GetTemplateObject() {
    DetailArray = new Array();
   
    $("table[id='category']").each(function (i, val) {
        var category = {};
        category.text = $($(val).find("input").get(0)).val();
        category.id = $($(val).find("input").get(1)).val();
        category.reportCategory = $($(val).find("input").get(2)).val();
        category.fields = [];
        var subTable = $(val).find("table");
        subTable.find("tr:gt(0)").each(function (i, val) {
            var tr = $(val);
            var field = {};
            field.id = $(tr.find("input").get(0)).val();
            field.type = $(tr.find("select")).val();
            if ($(tr.find("input[type='checkbox']")).attr("checked")) {
                field.isRequired = true;
            }
            else {
                field.isRequired = false;
            }
            field.label = $(tr.find("input").get(2)).val();
            if (field.type == 2) {
                field.options = $(tr.find("input").get(3)).val().split(',');
            }
            category.fields.push(field);
        });

        DetailArray.push(category);       
    });
    
    DetailArray.sort(comapre);       
}

function CheckInput() {
    var checkStatus = true;

    $("input[type='text']").removeClass("redBorder");
    $(".errorSpan").text("");

    $("input[type='text']").each(function (i, val) {

        if ($(val).attr("id") == "option") {
            if ($(val).parent().parent().find("select").val() == "2") {

                if ($(val).val() == "") {
                    $(val).addClass("redBorder");
                    checkStatus = false;
                }
            }
        }
        else {
            if ($(val).val() == "") {
                $(val).addClass("redBorder");
                checkStatus = false;
            }
        }

        if ($(val).val().indexOf('<') >= 0
                     || $(val).val().indexOf('>') >= 0
                     || $(val).val().indexOf('"') >= 0
                     || $(val).val().indexOf("'") >= 0) {
            $(val).addClass("redBorder");
            checkStatus = false;
            $(".errorSpan").text('输入包含非法字符： <，>，",\'');
        }
    });

    if (checkStatus) {
        $("input[type='text']").each(function (i, val) {

            if ($(val).attr("id") == "option") {
                if ($(val).parent().parent().find("select").val() == "1") {

                    if ($(val).val() != "") {
                        $(val).addClass("redBorder");
                        $(".errorSpan").text('字段类型为文本框时，选项值必须为空');
                        checkStatus = false;
                    }
                }
            }
        });
        
    }

    return checkStatus;

}
function GenerateTemplate() {
    var divContainer = $("#divCategories");
    divContainer.html("");
    var table, tr, td;
    var subTable, subTr, subTd, ddlType, cbRequired;
    for (var i in DetailArray) {
        table = CreateNewCategory();
        $(table.find("input").get(0)).val(DetailArray[i].text);
        $(table.find("input").get(1)).val(DetailArray[i].id);
        $(table.find("input").get(2)).val(DetailArray[i].reportCategory);
        subTable = table.find("table");
        for (var j in DetailArray[i].fields) {
            subTr = CreateNewfield();
            $(subTr.find("input").get(0)).val(DetailArray[i].fields[j].id);
            $(subTr.find("select").get(0)).val(DetailArray[i].fields[j].type);
            if (DetailArray[i].fields[j].isRequired) {
                $(subTr.find("input").get(1)).attr("checked", "checked");
            }
            $(subTr.find("input").get(2)).val(DetailArray[i].fields[j].label);
            $(subTr.find("input").get(3)).val(GetOptionString(DetailArray[i].fields[j].options));

            subTr.appendTo(subTable);

        }
        table.appendTo(divContainer);
    }
}

function NewTable() {
    return $("<table class='tableEdit'></table>");
}

function NewTr() {
    return $("<tr></tr>");
}

function newTd() {
    return $("<td></td>");
}

function NewFieldsTypeDdl() {
    return $("<select><option value='1'>文本框</option><option value='2'>下拉框</option></select>");
}

function NewFieldsRequiredCheckbox() {
    return $("<input type='checkbox' value='true' />");
}

function NewSubTable() {
    return $("<table><thead><tr><th style='width:8%'>编号</th><th style='width:10%'>类型</th><th style='width:10%'>必填项</th><th style='width:15%'>名称</th><th>选项</th><th>操作</th></tr></thead></table>");
}


function newTdWithClass(css) {
    return $("<td class='" + css + "'></td>");
}

function NewTextbox() {
    return $("<input type='text'/>")
}

function GetOptionString(value) {
    var result = "";
    for (var i in value) {
        result = result + value[i] + ","
    }
    if (result.length > 0) {
        result = result.substr(0, result.length - 1);
    }
    return result;
}

function CreateNewCategory() {
    var table, tr, td;
    table = NewTable();
    table.attr("id","category");

    tr = NewTr();
    td = newTdWithClass("label");
    td.addClass("title"); 
    td.html("分类名称");
    td.appendTo(tr);
    td = newTd();
    td.addClass("title");
    NewTextbox().appendTo(td);

    var hDeleteCategory = $("<img src='../../Images/grid/delete.png' style='width:22px;height:22px;' title='删除分类'/>");
    console.log(hDeleteCategory);  
    hDeleteCategory.click(function () {
        if (confirm('确定删除该分类吗？')) {
            $(this).parent().parent().parent().parent().remove();
        }
        return false;
    });
    hDeleteCategory.appendTo(td);
    td.appendTo(tr);
    tr.appendTo(table);

    tr = NewTr();
    td = newTdWithClass("label");
    td.html("编号");
    td.appendTo(tr);
    td = newTd();
    NewTextbox().appendTo(td);
    td.appendTo(tr);
    tr.appendTo(table);

    tr = NewTr();
    td = newTdWithClass("label");
    td.html("报表分类");
    td.appendTo(tr);
    td = newTd();
    NewTextbox().appendTo(td);
    td.appendTo(tr);
    tr.appendTo(table);

    tr = NewTr();
    td = newTdWithClass("label");
    td.html("字段");
    td.appendTo(tr);
    td = newTd();

    var hAddField = $("<img src='../../Images/grid/plus.png' style='width:24px;height:24px;float:right; margin-right:10px;' title='添加新字段'/>");

    hAddField.click(function () {
        var tr = CreateNewfield();
        tr.appendTo($(this).parent().find("table"));
        return false;
    });
    hAddField.appendTo(td);

    subTable = NewSubTable();

    subTable.appendTo(td);
    td.appendTo(tr);
    tr.appendTo(table);

    return table;
}

function CreateNewfield() {
    var subTr, subTd, ddlType, cbRequired;
    subTr = NewTr();

    subTd = newTd();
    NewTextbox().css("width", "60px").appendTo(subTd);
    subTd.appendTo(subTr);

    subTd = newTd();
    ddlType = NewFieldsTypeDdl().css("width", "80px");
    ddlType.appendTo(subTd);
    subTd.appendTo(subTr);

    subTd = newTd();
    cbRequired = NewFieldsRequiredCheckbox();
    cbRequired.appendTo(subTd);
    $("<span>必填项</span>").appendTo(subTd);
    subTd.appendTo(subTr);

    subTd = newTd();   
    NewTextbox().css("width", "120px").appendTo(subTd);
    subTd.appendTo(subTr);

    subTd = newTd();
    NewTextbox().css("width", "95%").attr("id","option").appendTo(subTd);    
    subTd.appendTo(subTr);

    subTd = newTd();
    subTd.css("width", "40px");
    var hDelete = $("<img style='clear: both; display: block; margin:auto; ' src='../../Images/grid/delete.png' title='删除'/>");
    hDelete.click(function () {
        if (confirm('确定删除该字段吗？')) {
            $(this).parent().parent().remove();
        }
        return false;
    });
    hDelete.appendTo(subTd);
    subTd.appendTo(subTr);

    return subTr;
}